import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { LOGIN_TOKEN } from '@/global/constants'
import { localCache } from '@/utils/cache'

class XYRequest {
  // axios实例
  instance: AxiosInstance
  constructor(config: AxiosRequestConfig) {
    //使用axios.create创建axios实例，beseUrl以及相关配置在new的时候参数的形式传过来
    this.instance = axios.create(config)

    // 拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 每次请求都携带token
        const token = localCache.getCache(LOGIN_TOKEN)
        if (token) {
          config.headers.token = `${token}`
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        return res.data
      },
      (err) => {
        return err
      }
    )
  }

  // 封装网络请求的方法
  request(config: AxiosRequestConfig) {
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get(config: AxiosRequestConfig) {
    return this.request({ ...config, method: 'GET' })
  }
  post(config: AxiosRequestConfig) {
    return this.request({ ...config, method: 'POST' })
  }
  delete(config: AxiosRequestConfig) {
    return this.request({ ...config, method: 'DELETE' })
  }
  patch(config: AxiosRequestConfig) {
    return this.request({ ...config, method: 'PATCH' })
  }

  put(param: { data?: any; url: string }) {
    return this.request({ ...param, method: 'PUT' })
  }
}

export default XYRequest
